package com.moxiao.yfjh.module.maker.controller.admin.matchmakerRecord;

import com.moxiao.yfjh.framework.common.pojo.CommonResult;
import com.moxiao.yfjh.framework.common.pojo.PageResult;
import com.moxiao.yfjh.framework.excel.core.util.ExcelUtils;
import com.moxiao.yfjh.framework.operatelog.core.annotations.OperateLog;
import com.moxiao.yfjh.module.blind.controller.admin.sessionRecord.vo.SessionRecordExportReqVO;
import com.moxiao.yfjh.module.blind.dal.dataobject.member.BlindMemberUserDO;
import com.moxiao.yfjh.module.blind.dal.dataobject.sessionRecord.SessionRecordDO;
import com.moxiao.yfjh.module.blind.service.member.BlindMemberUserService;
import com.moxiao.yfjh.module.blind.service.sessionRecord.SessionRecordService;
import com.moxiao.yfjh.module.maker.controller.admin.matchMakerStringing.vo.MatchmakerStringingExportReqVO;
import com.moxiao.yfjh.module.maker.controller.admin.matchmakerRecord.vo.*;
import com.moxiao.yfjh.module.maker.controller.admin.memberStringing.vo.MatchmakerMemberStringingExportReqVO;
import com.moxiao.yfjh.module.maker.controller.admin.memberStringing.vo.MatchmakerMemberStringingUpdateReqVO;
import com.moxiao.yfjh.module.maker.convert.matchmakerRecord.MatchmakerRecordConvert;
import com.moxiao.yfjh.module.maker.dal.dataobject.matchMakerStringing.MatchmakerStringingDO;
import com.moxiao.yfjh.module.maker.dal.dataobject.matchmakerInfo.MatchmakerInfoDO;
import com.moxiao.yfjh.module.maker.dal.dataobject.matchmakerRecord.MatchmakerRecordDO;
import com.moxiao.yfjh.module.maker.dal.dataobject.memberStringing.MatchmakerMemberStringingDO;
import com.moxiao.yfjh.module.maker.service.matchMakerStringing.MatchmakerStringingService;
import com.moxiao.yfjh.module.maker.service.matchmakerInfo.MatchmakerInfoService;
import com.moxiao.yfjh.module.maker.service.matchmakerRecord.MatchmakerRecordService;
import com.moxiao.yfjh.module.maker.service.memberStringing.MatchmakerMemberStringingService;
import com.moxiao.yfjh.module.system.api.user.AdminUserApi;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.moxiao.yfjh.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.moxiao.yfjh.framework.common.pojo.CommonResult.success;
import static com.moxiao.yfjh.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static com.moxiao.yfjh.module.maker.enums.ErrorCodeConstants.MATCHMAKER_MEMBER_NOT_EXISTS;

@Tag(name = "管理后台 - 相亲红娘记录")
@RestController
@RequestMapping("/maker/matchmaker-record")
@Validated
public class MatchmakerRecordController {

    @Resource
    private MatchmakerRecordService matchmakerRecordService;

    @Resource
    private MatchmakerInfoService matchmakerInfoService;

    @Resource
    private MatchmakerMemberStringingService stringingService;

    @Resource
    private MatchmakerMemberStringingService matchmakerMemberStringingService;

    @Resource
    private MatchmakerStringingService matchmakerStringingService;

    @Resource
    private BlindMemberUserService memberUserService;

    @Resource
    private SessionRecordService sessionRecordService;

    @Resource
    private AdminUserApi adminUserApi;


    @PostMapping("/create")
    @Operation(summary = "创建相亲红娘记录")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:create')")
    public CommonResult<Long> createMatchmakerRecord(@Valid @RequestBody MatchmakerRecordCreateReqVO createReqVO) {
        return success(matchmakerRecordService.createMatchmakerRecord(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新相亲红娘记录")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:update')")
    public CommonResult<Boolean> updateMatchmakerRecord(@Valid @RequestBody MatchmakerRecordUpdateReqVO updateReqVO) {
        matchmakerRecordService.updateMatchmakerRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除相亲红娘记录")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:delete')")
    public CommonResult<Boolean> deleteMatchmakerRecord(@RequestParam("id") Long id) {
        matchmakerRecordService.deleteMatchmakerRecord(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得相亲红娘记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:query')")
    public CommonResult<MatchmakerRecordRespVO> getMatchmakerRecord(@RequestParam("id") Long id) {
        MatchmakerRecordDO matchmakerRecord = matchmakerRecordService.getMatchmakerRecord(id);
        return success(MatchmakerRecordConvert.INSTANCE.convert(matchmakerRecord));
    }

    @GetMapping("/list")
    @Operation(summary = "获得相亲红娘记录列表")
    @Parameter(name = "ids", description = "编号列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:query')")
    public CommonResult<List<MatchmakerRecordRespVO>> getMatchmakerRecordList(@RequestParam("ids") Collection<Long> ids) {
        List<MatchmakerRecordDO> list = matchmakerRecordService.getMatchmakerRecordList(ids);
        return success(MatchmakerRecordConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @Operation(summary = "获得相亲红娘记录分页")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:query')")
    public CommonResult<PageResult<MatchmakerRecordRespVO>> getMatchmakerRecordPage(@Valid MatchmakerRecordPageReqVO pageVO) {
        pageVO.setMemberId(pageVO.getUserId());
        BlindMemberUserDO memberUser = memberUserService.getMemberUser(pageVO.getMemberId());
        if (Objects.isNull(memberUser)) {
            throw exception(MATCHMAKER_MEMBER_NOT_EXISTS);
        }
        PageResult<MatchmakerRecordDO> pageResult = matchmakerRecordService.getMatchmakerRecordPage(pageVO);
        PageResult<MatchmakerRecordRespVO> matchmakerRecordRespVOPageResult = MatchmakerRecordConvert.INSTANCE.convertPage(pageResult);
        if (Objects.nonNull(matchmakerRecordRespVOPageResult)) {
            if (CollectionUtils.isNotEmpty(matchmakerRecordRespVOPageResult.getList())) {
                matchmakerRecordRespVOPageResult.getList().forEach(s -> {
                    List<MatchmakerStringingDO> matchmakerStringingList = new ArrayList<>();
                    if (2 == memberUser.getSex()) {
                        matchmakerStringingList = matchmakerStringingService.getMatchmakerStringingList(new MatchmakerStringingExportReqVO().setMatchmakerId(s.getMatchmakerId()).setWomanId(pageVO.getMemberId()));
                    } else {
                        matchmakerStringingList = matchmakerStringingService.getMatchmakerStringingList(new MatchmakerStringingExportReqVO().setMatchmakerId(s.getMatchmakerId()).setManId(pageVO.getMemberId()));
                    }
                    if (CollectionUtils.isNotEmpty(matchmakerStringingList)) {
                        s.setPulledNum(matchmakerStringingList.size());
                    } else {
                        s.setPulledNum(0);
                    }
                    //            todo 返回recordId
                    List<SessionRecordDO> sessionRecordList = sessionRecordService.getSessionRecordList(new SessionRecordExportReqVO().setFounder(pageVO.getMemberId().toString()).setParticipants(String.valueOf(s.getMatchmakerId())));
                    if (CollectionUtils.isNotEmpty(sessionRecordList)) {
                        s.setRecordId(sessionRecordList.get(0).getRecordId());
                    } else if (CollectionUtils.isEmpty(sessionRecordList)) {
                        sessionRecordList = sessionRecordService.getSessionRecordList(new SessionRecordExportReqVO().setFounder(String.valueOf(s.getMatchmakerId())).setParticipants(pageVO.getMemberId().toString()));
                        if (CollectionUtils.isNotEmpty(sessionRecordList)) {
                            s.setRecordId(sessionRecordList.get(0).getRecordId());
                        }
                    }
                });
            }

        }
        return success(matchmakerRecordRespVOPageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出相亲红娘记录 Excel")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:export')")
    @OperateLog(type = EXPORT)
    public void exportMatchmakerRecordExcel(@Valid MatchmakerRecordExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<MatchmakerRecordDO> list = matchmakerRecordService.getMatchmakerRecordList(exportReqVO);
        // 导出 Excel
        List<MatchmakerRecordExcelVO> datas = MatchmakerRecordConvert.INSTANCE.convertList02(list);
        ExcelUtils.write(response, "相亲红娘记录.xls", "数据", MatchmakerRecordExcelVO.class, datas);
    }

    @GetMapping("/editMatchmaker")
    @Operation(summary = "变更红娘（传红娘id和会员id）")
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:editMatchmaker')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> editMatchmaker(@Valid @RequestBody MatchmakerRecordCreateReqVO editReqVO) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = simpleDateFormat.format(new Date());

//        向用户、红娘表里修改记录
        List<MatchmakerMemberStringingDO> matchmakerMemberStringingList = matchmakerMemberStringingService.getMatchmakerMemberStringingList(new MatchmakerMemberStringingExportReqVO().setMemberId(editReqVO.getMemberId()));
        if (CollectionUtils.isNotEmpty(matchmakerMemberStringingList)){
            Long id = matchmakerMemberStringingList.get(0).getId();
            MatchmakerMemberStringingUpdateReqVO matchmakerMemberStringingUpdateReqVO = new MatchmakerMemberStringingUpdateReqVO();
            matchmakerMemberStringingUpdateReqVO.setId(id);
            matchmakerMemberStringingUpdateReqVO.setMatchmakerId(editReqVO.getMatchmakerId());
            matchmakerMemberStringingService.updateMatchmakerMemberStringing(matchmakerMemberStringingUpdateReqVO);
        }

//        1.将原来的红娘服务停止
        Long oldId = matchmakerRecordService.selectMatchmakerRecordByMemberId(editReqVO.getMemberId());
        MatchmakerRecordUpdateReqVO updateReqVO = new MatchmakerRecordUpdateReqVO();
        updateReqVO.setId(oldId);
        updateReqVO.setServeTimeEnd(format);
        matchmakerRecordService.updateMatchmakerRecord(updateReqVO);

//        2.将变更的红娘插入
        MatchmakerInfoDO matchmakerInfo = matchmakerInfoService.getMatchmakerInfo(editReqVO.getMatchmakerId());
        BlindMemberUserDO memberUser = memberUserService.getMemberUser(editReqVO.getMemberId());
        editReqVO.setStringingNum(0);
        editReqVO.setServeTimeBegin(format);
        editReqVO.setMatchmakerName(matchmakerInfo.getName());
        editReqVO.setMemberName(memberUser.getNickname());
        matchmakerRecordService.createMatchmakerRecord(editReqVO);

        return success(true);

    }

    @GetMapping("/assignMatchmakers")
    @Operation(summary = "分配红娘(传红娘id和会员id)" )
    @PreAuthorize("@ss.hasPermission('maker:matchmaker-record:assignMatchmakers')")
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<Boolean> assignMatchmakers( MatchmakerRecordCreateReqVO assingReqVO) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String format = simpleDateFormat.format(new Date());

        //        向用户-红娘表里修改记录
        List<MatchmakerMemberStringingDO> matchmakerMemberStringingList = matchmakerMemberStringingService.getMatchmakerMemberStringingList(new MatchmakerMemberStringingExportReqVO().setMemberId(assingReqVO.getMemberId()));
        if (CollectionUtils.isNotEmpty(matchmakerMemberStringingList)){
            Long id = matchmakerMemberStringingList.get(0).getId();
            MatchmakerMemberStringingUpdateReqVO matchmakerMemberStringingUpdateReqVO = new MatchmakerMemberStringingUpdateReqVO();
            matchmakerMemberStringingUpdateReqVO.setId(id);
            matchmakerMemberStringingUpdateReqVO.setMatchmakerId(assingReqVO.getMatchmakerId());
            matchmakerMemberStringingService.updateMatchmakerMemberStringing(matchmakerMemberStringingUpdateReqVO);
        }

        MatchmakerInfoDO matchmakerInfo = matchmakerInfoService.getMatchmakerInfo(assingReqVO.getMatchmakerId());
        BlindMemberUserDO memberUser = memberUserService.getMemberUser(assingReqVO.getMemberId());
        assingReqVO.setStringingNum(0);
        assingReqVO.setServeTimeBegin(format);
        assingReqVO.setMatchmakerName(matchmakerInfo.getName());
        assingReqVO.setMemberName(memberUser.getNickname());
        matchmakerRecordService.createMatchmakerRecord(assingReqVO);
        return success(true);
    }

}
